package jupp;

import java.io.*;
import java.util.*;
import java.util.prefs.*;
import java.util.zip.*;

/**
* JuppMapGZIP compresses byte arrays before storing them in the Preferences
* back-end.
*
*/
public class JuppMapGZIP<V> extends JuppMap<V>
{
	private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
	public JuppMapGZIP(String name) throws BackingStoreException, IOException
	{
		super(name);
	}
	/**
	* putBytes applies GZIP compression to the array of bytes that is about to be
	* saved in the JuppMap back-end
	*
	* @param bytes an array of bytes which the JuppMap is about to write to its
	* backend
	*
	* @return an (hopefully smaller) array of bytes which are the compressed version
	* of the input byte array
	*/
	@Override
	protected byte[] putBytes(byte[] bytes) throws IOException
	{
		baos.reset();
		GZIPOutputStream gzos = new GZIPOutputStream(baos);
		gzos.write(bytes);
		gzos.close();
		return baos.toByteArray();
	}
	/**
	* getBytes decompresses an array of bytes previously GZIPped by putBytes.
	*
	* @param bytes a GZIPped array of bytes that JuppMap has retrieved from its back-end
	*
	* @return a decompressed version of the input bytes, ready for de-serialization
	* by JuppMap
	*/
	@Override
	protected byte[] getBytes(byte[] bytes) throws IOException
	{
		GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(bytes));
		int off = 0;
		int len = -1;
		baos.reset();
		byte[] buf = new byte[1<<12];
		while ((len = gzis.read(buf)) > -1)
		{
			off += len;
			baos.write(buf, 0, len);
		}
		return baos.toByteArray();
	}
}

